package org.zjx.app.action.gather;


import org.zjx.analysis.analyze.window.impl.PetAnalysis;
import org.zjx.app.action.AbstractWindowAction;
import org.zjx.command.entity.Pet;
import org.zjx.command.state.PetState;
import org.zjx.window.window.IWindow;

import java.awt.*;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.List;

public class GatherPetAction extends AbstractWindowAction {
    private PetAnalysis petAnalysis;
    
    public GatherPetAction(IWindow targetWindow) {
        super(targetWindow,true);
        analysis();
    }

    private void analysis() {
        petAnalysis = new PetAnalysis(targetWindow);
    }

    @Override
    public void open() {
        mouseAloofWindow(petAnalysis.windowArea == null? petAnalysis.getOriginBounds(): petAnalysis.windowArea);
        if (petAnalysis.isOpened()) return;
        targetWindow.actions().hotkey(KeyEvent.VK_ALT, KeyEvent.VK_O).delay(500);
        targetWindow.flushScreenshot();
        analysis();
        open();
    }

    @Override
    public void close() {
        analysis();
        if (!petAnalysis.isOpened()) return;
        targetWindow.actions().hotkey(KeyEvent.VK_ALT, KeyEvent.VK_O).delay(500);
        targetWindow.flushScreenshot();
        mouseAloofWindow(petAnalysis.windowArea == null? petAnalysis.getOriginBounds(): petAnalysis.windowArea);
        close();
    }

    @Override
    public void reSetWindow() {
        if (petAnalysis.isTransborder()) {
            Rectangle from = petAnalysis.conversion(petAnalysis.windowArea,petAnalysis.getRefImageArea());
            Rectangle to = petAnalysis.conversion(petAnalysis.getOriginBounds(),petAnalysis.getRefImageArea());
            targetWindow.actions().drag(from.x, from.y, to.x, to.y).delay(100);
            targetWindow.flushScreenshot();
            analysis();
        }
    }

    public void mouseAloofWindow(Rectangle rect) {
        if (petAnalysis.mouseInRect(rect)) {
            Point safePoint = petAnalysis.findLargestRemainingAreaCenter(rect);
            targetWindow.actions().gameMoveTo(safePoint.x, safePoint.y).delay(200);
            targetWindow.flushScreenshot();
            analysis();
        }
    }

    @Override
    protected void doExecute() throws Exception {
        open();
        reSetWindow();
        PetState petState = new PetState();
        stateManager.registerState(petState);
        
        List<Pet> pets = new ArrayList<>();
        for (int i = 0; i < Math.min(petAnalysis.getPetCount(),4);i++){
            while (petAnalysis.getChoosePetIndex() != i){
                targetWindow.actions().clickIn(petAnalysis.petIndex(i)).delay(200);
                targetWindow.flushScreenshot();
                analysis();
            }
            pets.add(petAnalysis.getPet());
        }
        petState.setPets(pets);
        close();
    }
}
